<template>
  <div>
    <div v-show="imgUploadShow" class="editor-custom-btn-container" style="margin-bottom:0px">
      <ImgUpload class="editor-upload-btn" @successCBK="imageSuccessCBK" />
    </div>

    <div :class="{fullscreen:fullscreen}" class="tinymce-container editor-container">
      <div :id="tinymceId2">
        <textarea
          :id="tinymceId"
          @change="handleChange"
          class="tinymce-textarea" />
      </div>
    </div>
  </div>
</template>

<script>
import ImgUpload from './components/ImgUpload'
// import { imgUpload } from '@/views/sys/modules/upload/upload'
import plugins from './plugins'
import toolbar from './toolbar'
import baseapi from '@/api/base'
// import menubar from './menubar'
// import './imageupload'
// import { setDateAndTime } from '@/utils/util'
// const axios = settingConfig.axios

const INIT = 0
const CHANGED = 2

export default {
  name: 'Tinymce',
  components: {
    ImgUpload
  },
  props: {
    tyid: {
      type: String,
      default: function () {
        return 'vue-tinymce-' + +new Date() + ((Math.random() * 1000).toFixed(0) + '')
      }
    },
    value: {
      type: String,
      default: ''
    },
    toolbar: {
      type: Array,
      required: false,
      default () {
        return []
      }
    },
    imgUploadShow: {
      type: Boolean,
      required: false,
      default: true
    },
    menubar: {
      type: String,
      default: 'file edit insert view format table'
    },
    height: {
      type: Number,
      required: false,
      default: 600
    },
    uploadUrl: {
      default: baseapi.imgUploadUrl,
      required: false,
      type: String
    },
    appId: {
      default: baseapi.huiwcore_app,
      required: false,
      type: String
    },
    idno: {
      default: 'idno',
      required: false,
      type: String
    },
    imgShowUrl: {
      default: baseapi.imgShowUrl,
      required: false,
      type: String
    }
  },
  data () {
    return {
      hasChange: false,
      hasInit: false,
      tinymceId: this.tyid,
      tinymceId2: 'div' + this.tyid,
      // tinymceId: '',
      fullscreen: false,
      languageTypeList: {
        'zh': 'zh_CN'
      },
      status: INIT
    }
  },
  computed: {
    language () {
      return this.languageTypeList[this.$store.getters.language]
    }
  },
  watch: {
    // value: function (val) {
    //   if (!this.hasChange && this.hasInit) {
    //     this.$nextTick(() =>
    //       window.tinymce.get(this.tinymceId).setContent(val || ''))
    //   }
    //   if (this.status === INIT || tinymce.activeEditor.getContent() !== val) {  // eslint-disable-line
    //     tinymce.activeEditor.setContent(val)  // eslint-disable-line
    //   }
    //   this.status = CHANGED
    // },
    value: function (val) {
      if (!this.hasChange && this.hasInit) {
        this.$nextTick(() =>
          window.tinymce.get(this.tinymceId).setContent(val || ''))
      }
      if (this.status === INIT || tinymce.activeEditor.getContent() !== val) {  // eslint-disable-line
        tinymce.activeEditor.setContent(val)  // eslint-disable-line
      }
      this.status = CHANGED
    },
    language () {
      this.destroyTinymce()
      this.$nextTick(() => this.initTinymce())
    }
  },
  mounted () {
    this.initTinymce()
  },
  activated () {
    if (window.tinymce.get(this.tinymceId)) {
      window.tinymce.execCommand('mceRemoveControl', true, this.tinymceId)
    }
    // this.$router.go(0)
    this.initTinymce()
  },
  deactivated () {
    this.destroyTinymce()
  },
  destroyed () {
    this.destroyTinymce()
  },
  methods: {
    initTinymce () {
      const _this = this
      window.tinymce.init({
        branding: false,
        language: 'zh_CN',
        // selector: '#tinymceId',
        selector: `#${this.tinymceId}`,
        fixed_toolbar_container: `#${this.tinymceId2}`,
        min_height: this.height - 15,
        max_height: this.height - 15,
        body_class: 'panel-body ',
        object_resizing: false,
        toolbar: this.toolbar.length > 0 ? this.toolbar : toolbar,
        menubar: false,
        plugins: plugins,
        autosave_ask_before_unload: false,
        toolbar_drawer: false,
        end_container_on_empty_block: true,
        // powerpaste_allow_local_images: true,
        code_dialog_height: 450,
        code_dialog_width: 1000,
        advlist_bullet_styles: 'square',
        advlist_number_styles: 'default',
        // imagetools_cors_hosts: ['www.tinymce.com', 'codepen.io'],
        default_link_target: '_blank',
        link_title: false,
        nonbreaking_force_tab: false, // inserting nonbreaking space &nbsp; need Nonbreaking Space Plugin
        paste_retain_style_properties: 'all',
        paste_word_valid_elements: '*[*]', // word需要它
        paste_data_images: false, // 粘贴的同时能把内容里的图片自动上传，非常强力的功能
        paste_convert_word_fake_lists: true, // 插入word文档需要该属性
        paste_webkit_styles: 'all',
        paste_merge_formats: true,
        paste_remove_styles: true,
        paste_remove_styles_if_webkit: true,
        paste_strip_class_attributes: true,
        paste_auto_cleanup_on_paste: true,
        convert_urls: false,
        relative_urls: false,
        remove_script_host: false,
        // powerpaste_word_import: 'clean',
        powerpaste_word_import: 'merge', // 参数可以是propmt, merge, clear，效果自行切换对比
        powerpaste_html_import: 'merge', // propmt, merge, clear
        // CONFIG: StyleSelect
        style_formats: [
          {
            title: '首行缩进',
            block: 'p',
            styles: { 'text-indent': '2em' }
          },
          {
            title: '行高',
            items: [
              { title: '1', styles: { 'line-height': '1' }, inline: 'span' },
              { title: '1.5', styles: { 'line-height': '1.5' }, inline: 'span' },
              { title: '2', styles: { 'line-height': '2' }, inline: 'span' },
              { title: '2.5', styles: { 'line-height': '2.5' }, inline: 'span' },
              { title: '3', styles: { 'line-height': '3' }, inline: 'span' }
            ]
          }
        ],
        fontsize_formats: `初号=42pt 小初=36pt 一号=26pt 小一=24pt 二号=22pt 小二=18pt 三号=16pt 小三=15pt 四号=14pt 小四=12pt 五号=10.5pt 小五=9pt 六号=7.5pt 小六=6.5pt 七号=5.5pt 八号=5pt 8pt=8pt 10pt=10pt 11pt=11pt 12.5pt=12.5pt 13pt=13pt 17pt=17pt 19pt=19pt 20pt=20pt 21pt=21pt 23pt=23pt 28pt=28pt 48pt=48pt 56pt=56pt 72pt=72pt`, // 第二步
        font_formats: `
          方正小标宋简体=方正小标宋简体;
          仿宋=仿宋;
          华文中宋=华文中宋;
          微软雅黑=微软雅黑;
          微软雅黑 Light=微软雅黑 Light;
          新宋体=新宋体;
          方正兰亭超细黑简体=方正兰亭超细黑简体;
          楷体=楷体;
          等线=等线;
          等线 Light=等线 Light;
          黑体=黑体;
          宋体=宋体;
          楷体=楷体;
          隶书=隶书;
          幼圆=幼圆;
          仿宋_GB2312=仿宋_GB2312;
          楷体_GB2312=楷体_GB2312;
          Malgun Gothic=Malgun Gothic;
          Andale Mono=andale mono,times;
          Arial=arial, helvetica,
          sans-serif;
          Arial Black=arial black, avant garde;
          Book Antiqua=book antiqua,palatino;
          Comic Sans MS=comic sans ms,sans-serif;
          Courier New=courier new,courier;
          Georgia=georgia,palatino;
          Helvetica=helvetica;
          Impact=impact,chicago;
          Symbol=symbol;
          Tahoma=tahoma,arial,helvetica,sans-serif;
          Terminal=terminal,monaco;
          Times New Roman=times new roman,times;
          Trebuchet MS=trebuchet ms,geneva;
          Verdana=verdana,geneva;
          Webdings=webdings;
          Wingdings=wingdings,zapf dingbats`,
        autosave_interval: '20s',
        image_advtab: true, // 开启图片上传的高级选项功能
        // cleanup: true,
        table_default_styles: {
          width: '100%',
          borderCollapse: 'collapse'
        },
        // image_title: true, // 是否开启图片标题设置的选择，这里设置否
        automatic_uploads: false, // 开启点击图片上传时，自动进行远程上传操作
        init_instance_callback: editor => {
          editor.on('init', (e) => {
            editor.setContent(_this.value)
          })
          // if (_this.value) {
          //   editor.setContent(_this.value)
          // }
          _this.hasInit = true
          editor.on('NodeChange Change KeyUp SetContent', () => {
            _this.hasChange = true
            _this.$emit('input', editor.getContent())
          })
        },
        setup (editor) {
          editor.on('FullscreenStateChanged', (e) => {
            _this.fullscreen = e.state
          }),
          editor.on("change",function (e) {
            _this.handleChange();
          })
        }
      }).then(() => {
        // console.log(_this.tinymceId)
        // console.log(window.tinymce.get(_this.tinymceId))
        window.tinymce.get(_this.tinymceId).setContent(_this.value)
      })
    },
    destroyTinymce () {
      const tinymce = window.tinymce.get(this.tinymceId)
      if (this.fullscreen) {
        tinymce.execCommand('mceFullScreen')
      }
      if (tinymce) {
        tinymce.destroy()
      }
    },
    setContent (value) {
      window.tinymce.get(this.tinymceId).setContent(value)
    },
    getContent () {
      window.tinymce.get(this.tinymceId).getContent()
    },
    imageSuccessCBK (arr) {
      const _this = this
      // let htmlStr = '<div style="width: 100%; margin: 0 auto; text-align: center;">'
      let htmlStr = '' // '<div style="width: 90%; margin-left: auto; margin-right: auto;text-align: center;" >'
      arr.forEach(v => {
        // console.log('v', v)
        if (v !== '') {
          v = this.imgShowUrl + v
          htmlStr = htmlStr + '<img style="display: block;max-width: 96%; margin-bottom: 20px; margin-left: auto; margin-right: auto;"  src="' + v + '" />'
          // const htmlStr1 = '<img style="width: 420px; height: 320px; margin-left: 5px; margin-bottom: 5px;" src="' + v + '" />'
          // htmlStr = htmlStr + htmlStr1
        }
      })
      htmlStr = htmlStr + '<br>' + ''
      window.tinymce.get(_this.tinymceId).insertContent(htmlStr)
      // window.tinymce.get(_this.tinymceId).insertContent(htmlStr)
    },
    handleChange (ed) {
      // this.$emit('change',ed.getBody().innerHTML)
      console.log(ed)
      // this.$emit('dataChanged', val)
    }
  }
}
</script>

<style scoped>
.tinymce-container {
   position: relative;
   line-height: normal;
 }
 .tinymce-container>>>.mce-fullscreen {
   z-index: 10000;
 }
 .tinymce-textarea {
   visibility: hidden;
   z-index: -1;
 }
 .editor-custom-btn-container {
   /* margin: -8px;
   position: absolute;
   left: 5px;
   top: 1px; */
   /*z-index: 2005;*/
 }
 .fullscreen .editor-custom-btn-container {
   z-index: 10000;
   position: fixed;
 }
 .editor-upload-btn {
   display: inline-block;
 }
</style>
